package station

import (
	"fmt"
	"github.com/gin-gonic/gin"
	logic2 "iot-base/auth/api/logic"
	"iot-base/auth/db"
	"iot-base/auth/logger"
	"iot-base/auth/model/iot"
	types2 "iot-base/auth/types"
	"strconv"
)

// ListStations 站列表.
func ListStations(c *gin.Context) {
	requestId, _ := c.Get("RequestId")
	uid := c.GetInt64("uid")
	resp := types2.NewResult(c)
	logic := logic2.NewStationLogic()
	var req types2.ReqStation
	err := c.ShouldBind(&req)
	if err != nil {
		resp.ErrorCode(types2.ParamsError, "")
		return
	}
	result, err := logic.FindStatingList(uid, req)
	if err != nil {
		logger.Log.Errorf("[%v] FindList err:=%v", requestId, err)
		resp.ErrorCode(types2.ExceptionError, "")
		return
	}
	list := result["list"].([]iot.Stations)
	mapList := make([]map[string]interface{}, 0, len(list))
	for index := range list {
		temp := map[string]interface{}{
			"area_id":   list[index].AreaID,
			"desc":      list[index].Desc,
			"level":     list[index].Level,
			"parent_id": list[index].ParentID,
			"s_name":    list[index].SName,
			"rule":      list[index].Rule,
			"uid":       list[index].UID,
		}
		temp["lon"], _ = strconv.ParseFloat(list[index].Lon, 64)
		temp["lat"], _ = strconv.ParseFloat(list[index].Lat, 64)
		temp["catalog_id"], _ = logic.GetStationType(list[index].UID)
		mapList = append(mapList, temp)
	}
	result["list"] = mapList
	resp.Success(result)
	return
}

// AddStations 新增站点.
func AddStations(c *gin.Context) {
	requestId, _ := c.Get("RequestId")
	uid := c.GetInt64("uid")
	fmt.Println(requestId, uid)
}

// EditGroupStations 组关联站点
func EditGroupStations(c *gin.Context) {
	uid := c.GetInt64("uid")
	requestId, _ := c.Get("RequestId")
	resp := types2.NewResult(c)
	var req types2.ReqEditGroupStation
	err := c.ShouldBind(&req)
	if err != nil {
		logger.Log.Errorf("[%s] err:=%v", requestId, err)
		resp.ErrorCode(types2.ParamsError, "")
		return
	}
	logic := logic2.NewStationLogic()
	err = logic.EditGroupStations(req.GroupId, req.StationIds)
	if err != nil {
		logger.Log.Errorf("[%s] err:=%v", requestId, err)
		resp.ErrorCode(types2.ExceptionError, err.Error())
		return
	}
	// 清除缓存
	redis := db.NewRedis()
	redis.Del(fmt.Sprintf(db.KeyUserThingId+"#%v", uid))
	resp.Success(gin.H{})
}

// GetUserStation 用户设备.
func GetUserStation(c *gin.Context) {
	requestId, _ := c.Get("RequestId")
	uid, _ := c.Get("uid")
	resp := types2.NewResult(c)
	logic := logic2.NewStationLogic()
	list, err := logic.GetUserStations(uid.(int64))
	if err != nil {
		logger.Log.Errorf("[%s] err:=%v", requestId, err)
		resp.ErrorCode(types2.ExceptionError, err.Error())
		return
	}
	resp.Success(gin.H{"list": list})
}
